#pragma once

#include "Thread.h"
#include "SerialPort.h"

#include <string>
#include <ctime>
using namespace std;

typedef enum
{
	ES_MSG_WEIGHT = 1,
	ES_MSG_ZERO   = 2,
	ES_MSG_CONNECT = 3,
}EsMsgEn;

class ElecScale : public Thread
{
public:
	ElecScale(void);
	~ElecScale(void);

private:
	virtual int Run();

public:
	void startWeight( int frequence, bool readId );
	void endWeight();
	char* getScaleId();
	void SetIdCheck(bool en, string id);
	void GetIdCheck(string &stat, string &id);
	void setMsgReceiver( DWORD hwnd ) { msgReceiver = hwnd; }
	bool GetWeight(float &nw, float &tw);
	void StartZeroCheck(int sec, float devi);
	void EnableMsg(EsMsgEn);
	bool IsZeroDone();
	bool IsConnected();

private:
	void processMessage( int status, float weight, float tare );

	int readExact( unsigned char* buf, unsigned int len );
	int write( unsigned char* buf, unsigned int len );

	bool weighting();

	bool parseWeightValue(unsigned char *buf, int size);
	bool parseScaleId(unsigned char *buf, int size);

	bool ReadId();
	bool ReadWeight();

private:
	int freq;

	bool isReadingScaleId;
	bool needCheckScaleId;

	char ScaleId[8];
	string m_Id;

	unsigned char weight_data[32];
	int weight_data_length;

	DWORD msgReceiver;

	SerialPort ComDev;
	float NWeight;
	float TWeight;
	bool StatOk;
	bool Lock;

	UINT MsgEn_Weight:1;
	UINT MsgEn_Zero:1;
	UINT MsgEn_CONNECT:1;
	UINT ZeroStart:1;
	UINT ZeroDone:1;

	int ZeroTime;
	float ZeroDevi;

	bool Connected;

	time_t ZStartTime;
};
